<template>
  <div class="role">
    <div class="header">
      <pagesSearch :form-config="roleForm"></pagesSearch>
    </div>
    <pagesContent
      :tableConfig="tableConfig"
      pages-name="role"
      @emitHandAddClick="handAddClick"
      @emitHandEditClick="handEditClick"
    >
      <template v-slot:headerHand>
        <el-button type="primary" @click="handAddClick">添加角色</el-button>
      </template>
    </pagesContent>
    <pagesContentAdd
      ref="pagesModelRef"
      title="添加用户"
      :form-config="addForm"
      :defaultConfig="defaultConfig"
      page-name="role"
      :treeForm="treeForm"
    >
      <div class="tree">
        <el-tree
          ref="treeFormRef"
          :props="{ label: 'name', children: 'children' }"
          :data="menuList"
          node-key="id"
          show-checkbox
          @check="handSelectTreeClick"
        />
      </div>
    </pagesContentAdd>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, nextTick } from 'vue'
import pagesContent from '@/components/pages-content/pages-content.vue'
import { tableConfig } from '@/views/main/system/role/config/table-config'
import pagesSearch from '@/components/pages-search/pages-search.vue'
import { roleForm } from '@/views/main/system/role/config/search-type'
import { addForm } from '@/views/main/system/role/config/addTable-config'
import { useContentModel } from '@/Hook/use-content-model'
import pagesContentAdd from '@/components/pages-content-add/pages-content-add.vue'
import { useStore } from 'vuex'
import { getCurrentLeaf } from '@/utils/map-menu'
import { ElTree } from 'element-plus'

export default defineComponent({
  name: 'role-pages',
  components: {
    pagesContent,
    pagesSearch,
    pagesContentAdd
  },
  setup() {
    const treeFormRef = ref<InstanceType<typeof ElTree>>()
    //点击编辑回调函数
    const EditCallback = (item: any) => {
      const leafList = getCurrentLeaf(item.menuList)
      nextTick(() => {
        //设置el-tree的选中状态
        treeFormRef?.value?.setCheckedKeys(leafList, false)
      })
    }
    const treeForm = ref({})
    const handSelectTreeClick = (d1: any, d2: any) => {
      const checkedKeys = d2.checkedKeys
      const halfCheckedKeys = d2.halfCheckedKeys
      const menuList = [...checkedKeys, ...halfCheckedKeys]
      treeForm.value = { menuList }
    }
    //点击编辑回调函数
    const [pagesModelRef, defaultConfig, handAddClick, handEditClick] =
      useContentModel(undefined, EditCallback)
    const store = useStore()
    const menuList = computed(() => {
      return store.state.menuList
    })
    return {
      tableConfig,
      roleForm,
      defaultConfig,
      pagesModelRef,
      handAddClick,
      handEditClick,
      addForm,
      menuList,
      treeForm,
      treeFormRef,
      handSelectTreeClick
    }
  }
})
</script>

<style scoped>
.header {
  margin-bottom: 10px;
  background: #fff;
}
.tree {
  margin-left: 130px;
}
</style>
